from helpers import utils
from helpers import datetime

def get_frequencies(date):
    frequencies = utils.read_json(utils.get_path('KEYWORDS_PATH', date))
    return frequencies if frequencies else {}

def get_frequencies_in_range(start_date, end_date):
    result = {}
    for date in datetime.range_iterator(start_date, end_date):
        for key, value in get_frequencies(date).items():
            result[key] = result.get(key, 0) + value
    return result

def get_top_k_words_in_range(start_date, end_date, k):
    frequencies = get_frequencies_in_range(start_date, end_date)
    sorted_frequencies = sorted(frequencies.items(), key=lambda item: item[1], reverse=True)
    return [item[0] for item in sorted_frequencies[:k]]

def get_word_counts_in_range(start_date, end_date, words):
    result = {}
    for date in datetime.range_iterator(start_date, end_date):
        frequencies = get_frequencies(date)
        result[date] = {word: frequencies.get(word, 0) for word in words}
    return result

def get_recent_frequencies(days):
    start_date, end_date = datetime.get_date_range(days)
    return get_frequencies_in_range(start_date, end_date)

def get_recent_top_k_frequencies(days, k):
    frequencies = get_recent_frequencies(days)
    sorted_frequencies = sorted(frequencies.items(), key=lambda item: item[1], reverse=True)
    return sorted_frequencies[:k]
